package com.cwz.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwz.gulimall.product.service.CategoryBrandRelationService;
import com.cwz.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cwz.gulimall.product.dao.CategoryDao;
import com.cwz.gulimall.product.entity.CategoryEntity;
import com.cwz.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    //使用sprin-cache操作redis
    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Catagorys = getParent_cid(selectList, 0L);
        Map<String, List<Catalog2Vo>> collect = level1Catagorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(item -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    List<CategoryEntity> categoryEntities1 = getParent_cid(selectList, item.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (categoryEntities1 != null) {
                        catalog3Vos = categoryEntities1.stream().map(item1 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), item1.getCatId().toString(), item1.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());

            }
            return catalog2Vos;
        }));
        return collect;
    }

    //使用StringRedisTemplate操作缓存
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        Map<String, List<Catalog2Vo>> catalog = null;
        if (StringUtils.isEmpty(catalogJSON)) {
            catalog = getCatalogJsonFromDBWithRedissonLock();
            return catalog;
        }
        catalog = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return catalog;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedissonLock() {

        //本地锁
//        synchronized (this) {

//        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
//        if (!StringUtils.isEmpty(catalogJSON)) {
//            Map<String, List<Catalog2Vo>> catalog = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
//            });
//            return catalog;
//        }
        RLock lock = redissonClient.getLock("catalogJSON-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> catalogFromDB;
        try {
            catalogFromDB = getCatalogFromDB();
        } finally {
            lock.unlock();
        }

//            String lock = stringRedisTemplate.opsForValue().get("catalogLock");
//            if (uuid.equals(lock)) {
//                stringRedisTemplate.delete("catalogLock");
//            } // 不具备原子性,使用lua脚本
        return catalogFromDB;
    }

    private Map<String, List<Catalog2Vo>> getCatalogFromDB() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catalog2Vo>> catalog = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return catalog;
        }

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Catagorys = getParent_cid(selectList, 0L);
        Map<String, List<Catalog2Vo>> collect = level1Catagorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(item -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    List<CategoryEntity> categoryEntities1 = getParent_cid(selectList, item.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (categoryEntities1 != null) {
                        catalog3Vos = categoryEntities1.stream().map(item1 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), item1.getCatId().toString(), item1.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());

            }
            return catalog2Vos;
        }));
        stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(collect), 1, TimeUnit.DAYS);
        return collect;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> level1Menus = list.stream()
                .filter(item -> item.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, list));
                    return menu;
                }).sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                })
                .collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public boolean removeMenusByIds(List<Long> asList) {
        List<CategoryEntity> list = this.list();
        for (Long id : asList) {
            CategoryEntity categoryEntity = getById(id);
            List<CategoryEntity> children = getChildren(categoryEntity, list);
            if (children.size() != 0) {
                return false;
            }
        }
        removeByIds(asList);
        return true;
    }

    @Override
    public Long[] getCategoryPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        CategoryEntity categoryEntity = getById(catelogId);
        path.add(catelogId);
        while (categoryEntity.getParentCid() != 0) {
            path.add(categoryEntity.getParentCid());
            categoryEntity = getById(categoryEntity.getParentCid());
        }
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    private List<CategoryEntity> getChildren(CategoryEntity current, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(item -> item.getParentCid() == current.getCatId())
                .map((item) -> {
                    item.setChildren(getChildren(item, all));
                    return item;
                }).sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                }).collect(Collectors.toList());
        return children;
    }

}